<?php
namespace app\admin\controller;
use think\facade\Db;
use think\facade\View;
class StockLog extends Base
{
    public function index(){
        if(IS_AJAX){
            $page = input('page');
            $limit = input('limit')?:15;
            $map = [];
            if(input('goods_id')){
                $map['s.goods_id'] = input('goods_id');
            }
            if(input('goods_name')){
                $map['s.goods_name'] = ['like','%'.input('goods_name').'%'];
            }
            if(input('time_start') && input('time_end')){
                $time_start = strtotime(input('time_start'));
                $time_end = strtotime(input('time_end'));
                $map['s.ctime'] = ['between',[$time_start,$time_end]];
            }
            $count = Db::name('stock_log')->alias('s')->where($map)->count();

            $field = 's.*';
            $list = Db::name('stock_log')
                ->alias('s')
                ->field($field)
                ->where($map)
                ->order('s.id desc ')
                ->page($page,$limit)
                ->select();
            if($list){
                foreach($list as $k=>$v){
                    $v['ctime'] = date('Y-m-d H:i:s',$v['ctime']);
                    $list[$k] = $v;
                }
            }
            return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$list]);
        }
        return View::fetch();
    }

    public function excel(){
        $map = [];
        if(input('goods_id')){
            $map['s.goods_id'] = input('goods_id');
        }
        if(input('goods_name')){
            $map['s.goods_name'] = ['like','%'.input('goods_name').'%'];
        }
        if(input('time_start') && input('time_end')){
            $time_start = strtotime(input('time_start'));
            $time_end = strtotime(input('time_end'));
            $map['s.ctime'] = ['between',[$time_start,$time_end]];
        }
        $count = Db::name('stock_log')->alias('s')->where($map)->count();

        $field = 's.*';
        $list = Db::name('stock_log')
            ->alias('s')
            ->field($field)
            ->where($map)
            ->order('s.id desc ')
            ->select();
        $title = ['ID','商品ID','商品名称','商品规格','订单号','库存','日志时间'];
        if($list){
            foreach($list as $k=>$v){
                $v['ctime'] = date('Y-m-d H:i:s',$v['ctime']);
                $list[$k] = $v;

                $arr = [
                    $v['id'],$v['goods_id'],$v['goods_name'],$v['goods_spec'],$v['order_sn'],$v['stock'],$v['ctime']
                ];
                $data[] = $arr;
            }
        }
        return json(['code'=>0,'msg'=>'查询成功','count'=>$count,'data'=>$data,'title'=>$title]);
        //dump($title);
        //dump($data);exit;
        $this->export_excel($title,$data);
    }
}
